<?php

require_once 'include/config.php';
require_once 'include/http.php';
require_once 'wechat.php';

//执行程序
$qrcode = new qrcode();
echo $qrcode->getQrcode();


class qrcode{
    
    
    private $appid = '';
    private $appsecret = '';
    private $http = '';
    
    public function __construct() {
        $this->appid = constant('APPID');
        $this->appsecret = constant('APPSECRET');
        $this->http = new http();
        //获取access_token
        $wechat = new wechat();
        $this->access_token = $wechat->getAccessToken();
    }
    
    public function getQrcode() {
//        p($_SERVER);
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$this->access_token}";
        if($_POST['type'] == 1){
            $data = '{"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$_POST['scene_id'].'}}}';
        }else{
            $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$_POST['scene_id'].'}}}';
        }
        $json = $this->http->http_request($url,$data);
        $ticket = json_decode($json,TRUE)['ticket'];
        
        $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".  urlencode($ticket);
        $img = $this->http->http_request($url);
        $name = time().".jpg";
        file_put_contents('./img/'.  $name, $img);
        
        $host = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'];
        
        return json_encode(['url' => $host.'/img/'.$name]);
    }
    
}

